import logging
import re

from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid_token, check_openid_token
from apps.users.models import User
from utils.response_code import RETCODE

logger=logging.getLogger('django')


class OauthQQURLView(View):
    def get(self,request):

        state=request.GET.get('next')

        qq=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                   redirect_uri=settings.QQ_REDIRECT_URI,
                   client_secret=settings.QQ_CLIENT_SECRET,
                   state=state


        )
        login_url=qq.get_qq_url()

       #
        # login_url = 'https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=101518219&redirect_uri=http://www.meiduo.site:8000/oauth_callback&state=test'
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})




class OauthQQUserView(View):
    def get(self, request, ):

        code = request.GET.get('code')
        if code is None:

            return http.HttpResponseBadRequest('参数有误')
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     client_secret=settings.QQ_CLIENT_SECRET,
        )
        token=qq.get_access_token(code)
        openid=qq.get_open_id(token)

        try:
            qquser=OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            openid_token=generic_openid_token(openid)

            return render(request,'oauth_callback.html',context={'openid':openid_token})
        else:

            user = qquser.user

            login(request, user)
            next=request.GET.get("state")
            if next:
                response=redirect( next)
            else:
                response = redirect(reverse('contents:index'))
            response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

            return response


        return render(request, 'oauth_callback.html')

    def post(self, request,):
        data = request.POST
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code_client = data.get('sms_code')
        access_token = data.get('access_token')

        if not all([mobile,password,sms_code_client,access_token]):
            return http.HttpResponseBadRequest("参数不全")
        # if  not re.match(r'^1[3-9]{9}$',mobile):
        #     return http.HttpResponseBadRequest("手机号不满足条件")
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('手机号不满足条件')

        if  not re.match(r'^[0-9a-zA-Z_-]{8,20}$',password):
            return http.HttpResponseBadRequest("密码格式不满足")
        redis_conn = get_redis_connection("code")
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.HttpResponseBadRequest("验证码已经过期")
        # if sms_code_server.decode() !=sms_code_client:
        if sms_code_server.decode() != sms_code_client:
            return http.HttpResponseBadRequest('短信验证码不一致')
        openid=check_openid_token(access_token)
        if openid is None:
            return http.HttpResponseBadRequest('openid错误')
        try:
            user=User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user=User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile,
            )
            pass
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('密码错误')
        try:
            OAuthQQUser.objects.create(
                openid=openid,
                user=user
            )
        except Exception as e:
            logger.error(e)
            return  http.HttpResponseBadRequest('数据库错误')
        # login(request,user)
        # response=redirect(reverse('contents:index'))
        # response.set_cookie('username',user.username,max_age=14*24*3600)
        # return response
        login(request, user)
        # 5.cookie
        response = redirect(reverse('contents:index'))

        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)
        # 6.返回相应
        return response

        pass

        pass
    ###################################################itsdangerous###################
 # #加密处理
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from  meiduo_mall import settings
s=Serializer(settings.SECRET_KEY,300)
data= {'openid':'abcde'}
token=s.dumps(data)
token.decode()
#解密处理
from itsdangerous import  TimedJSONWebSignatureSerializer as Serializer
s=Serializer(settings.SECRET_KEY,300)
s.loads(token)
##########################解密失败＃＃＃＃＃＃＃＃＃＃＃　
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from  meiduo_mall import settings
s=Serializer(settings.SECRET_KEY,1)
data= {'openid':'abcde'}
token=s.dumps(data)
token.decode()
#加密数据失败会报异常
##########################解密失败　　　　数据被篡改＃＃＃＃＃＃＃＃＃＃＃　
#token 被篡改会报异常


